package com.hs.myshell;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;

import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.internal.UIPlugin;

import com.hs.myshell.data.DataAccess;
import com.hs.myshell.data.SshSetting;
import com.hs.myshell.utils.StringUtils;
import com.hs.myshell.views.tree.TreeObject;
import com.hs.myshell.views.tree.TreeParent;

/**
 * 11.1.10
 * @author Administrator
 *
 */
public class EditorDialog extends TrayDialog {

	private SshSetting sshSetting;
	private TreeObject sshKey;
	private TreeParent parent;
	private TreeViewer treeViewer;
	private IViewSite site;
	private Boolean add;
	
	public EditorDialog(Shell shell,TreeParent parent,TreeObject sshKey,TreeViewer viewer,IViewSite viewSite,Boolean add) {
		super(shell);
		this.add = add;
		this.parent = parent;
		this.sshKey = sshKey;
		this.treeViewer = viewer;
		this.site = viewSite;
		DataAccess instance = DataAccess.getInstance();
		instance.init();//TODO delete
		this.sshSetting = instance.get(sshKey);
	}
	
//	protected Control createContents(Composite parent) {
//        Composite container = new Composite(parent, SWT.NONE);
//        final GridLayout gridLayout = new GridLayout();
//        gridLayout.numColumns = 1;
//        container.setLayout(gridLayout);
//
//        final Text text = new Text(container, SWT.BORDER);
//        text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
//
//        return container;
//    }
	
	public void setDialogTitle(String title) {
        if (this.getShell() != null && !this.getShell().isDisposed()) {
            this.getShell().setText(title);
        }

    }

	@Override
	protected Control createDialogArea(Composite parent) {
		// TODO Auto-generated method stub
		Control control = super.createDialogArea(parent);
		setDialogTitle("shh config");
		if (control instanceof Composite) {
			ScrolledComposite sc = new ScrolledComposite((Composite) control, 512);

			GridLayout layout = new GridLayout(1, true);
			layout.marginHeight = 0;
			layout.marginWidth = 0;
			layout.verticalSpacing = 0;
			layout.horizontalSpacing = 0;

			sc.setLayout(layout);
			sc.setLayoutData(new GridData(1808));

			sc.setExpandHorizontal(true);
			sc.setExpandVertical(true);

			Composite composite = new Composite(sc, 0);
			composite.setLayout(new GridLayout());

			createDialogAreaContent(composite);

			sc.setContent(composite);
			sc.setMinSize(composite.computeSize(-1, -1));

			control = sc;
		}
		
		return control;
	}
	
	@Override
	protected void okPressed() {
		//saveOrUpdate ssh config
		DataAccess.getInstance().saveOrUpdate(this.sshSetting);
//		ViewContentProvider newProvider = new ViewContentProvider(this.site);
//		ITreeContentProvider oldContentProvider = (ITreeContentProvider)viewer.getContentProvider();
//		TreeObject treeO = new TreeObject("haha"); 
//		oldContentProvider.inputChanged(viewer, sshKey, null);
//		oldContentProvider.inputChanged(viewer, oldContentProvider, newProvider);
//		viewer.setContentProvider(newProvider); //TODO 重新设置 内容 
//		viewer.setContentProvider(null);
		if(add) {
			parent.addChild(new TreeObject("newNode"));
		}else {
			sshKey.setName(sshSetting.getHost());//这样修改无效,再加一个下面的刷新即可
		}
		treeViewer.refresh();
		super.okPressed();
	}
	
	class ViewContentProvider implements ITreeContentProvider {
		private TreeParent invisibleRoot;
		private IViewSite site;

		public ViewContentProvider(IViewSite site) {
			super();
			this.site = site;
		}
		public Object[] getElements(Object parent) {
			if (parent.equals(this.site)) {
				if (invisibleRoot==null) initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}
		public Object getParent(Object child) {
			if (child instanceof TreeObject) {
				return ((TreeObject)child).getParent();
			}
			return null;
		}
		public Object [] getChildren(Object parent) {
			if (parent instanceof TreeParent) {
				return ((TreeParent)parent).getChildren();
			}
			return new Object[0];
		}
		public boolean hasChildren(Object parent) {
			if (parent instanceof TreeParent)
				return ((TreeParent)parent).hasChildren();
			return false;
		}
/*
 * We will set up a dummy model to initialize tree heararchy.
 * In a real code, you will connect to a real model and
 * expose its hierarchy.
 */
		private void initialize() {
			TreeObject to1 = new TreeObject("newContentProvider192.168.4.110");
			TreeObject to2 = new TreeObject("Leaf 2");
			TreeObject to3 = new TreeObject("Leaf 3");
			TreeParent p1 = new TreeParent("Parent 1");
			p1.addChild(to1);
			p1.addChild(to2);
			p1.addChild(to3);
			
			TreeObject to4 = new TreeObject("Leaf 4");
			TreeParent p2 = new TreeParent("Parent 2");
			p2.addChild(to4);
			
			TreeParent root = new TreeParent("Root");
			root.addChild(p1);
			root.addChild(p2);
			
			invisibleRoot = new TreeParent("");
			invisibleRoot.addChild(root);
		}
	}
	
	
	
	private Text hostText;
	private Text user;
	private Text timeout;
	private Text keepalive;
	private Text port;
	private Text password;
	
	protected void createDialogAreaContent(Composite parent) {
		Composite composite = new Composite(parent, 0);
		GridLayout gridLayout = new GridLayout(2, false);
		GridData gridData = new GridData(768);
		gridData.horizontalIndent = FieldDecorationRegistry.getDefault().getMaximumDecorationWidth();

		composite.setLayout(gridLayout);
		composite.setLayoutData(gridData);
		
		if (sshSetting == null) {
			//add
			sshSetting = new SshSetting();
		}
		Class<? extends SshSetting> class1 = sshSetting.getClass();
		Field[] fields = class1.getDeclaredFields();
		for (Field field : fields) {
			String name = field.getName();
			try {
				String value = (String) getter(sshSetting, name);  
				createTextField(composite, name,value); 
			} catch (SecurityException | IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
		
//		createTextField(composite, "HOST",sshSetting.getHost());            
//		createTextField(composite, "USER",sshSetting.getUser());            
//		createTextField(composite, "PASSWORD",sshSetting.getPassword());    
//		createTextField(composite, "TIMEOUT",sshSetting.getTimeout());      
//		createTextField(composite, "KEEPALIVE",sshSetting.getKeepalive());  
//		createTextField(composite, "PORT",sshSetting.getPort());            

//		this.hostText = createTextField(composite, "HOST",sshSetting.getHost());
//		this.user =     createTextField(composite, "USER",sshSetting.getUser());
//		this.password = createTextField(composite, "PASSWORD",sshSetting.getPassword());
//		this.timeout =  createTextField(composite, "TIMEOUT",sshSetting.getTimeout());
//		this.keepalive= createTextField(composite, "KEEPALIVE",sshSetting.getKeepalive());
//		this.port =     createTextField(composite, "PORT",sshSetting.getPort());
//		loadSettings();
	}
	
	 /* 
     *@param obj 操作的对象 
     *@param att 操作的属性 
     *@param value 设置的值 
     *@param type 参数的类型 
     */  
    public static void setter(Object obj, String att, Object value, Class<?>type){  
        try {  
            Method met = obj.getClass().  
                            getMethod("set" + initStr(att), type);  
            met.invoke(obj, value);  
        }catch (Exception e){  
            e.printStackTrace();  
        }  
    }  
    public static Object getter(Object obj, String att){  
        try {  
            Method met = obj.getClass().getMethod("get" + initStr(att));  
            Object invoke = met.invoke(obj);
            System.out.println(invoke);  
            return invoke;
        }catch (Exception e){  
            e.printStackTrace();  
        }
		return null;  
    }  
    public static String initStr(String old){   // 将单词的首字母大写  
        String str = old.substring(0,1).toUpperCase() + old.substring(1) ;  
        return str ;  
    }
	
	private Text createTextField(Composite composite, String labelTxt,String defaultValue) {
		Label ctlLabel = new Label(composite,SWT.LEFT);
		ctlLabel.setText(labelTxt + ":");
		GridData gridData = new GridData(768);
		Text text = new Text(composite,SWT.ARROW_LEFT);
		text.setData("identifier", labelTxt);
		text.setLayoutData(gridData);
		if (!StringUtils.isBlank(defaultValue)) {
			text.setText(defaultValue);
		}
//		text.addFocusListener(new FocusListener() {
//			
//			@Override
//			public void focusLost(FocusEvent e) {
//				 System.out.println("获得焦点"+e.getSource());
//				
//			}
//			
//			@Override
//			public void focusGained(FocusEvent e) {
//				Text targetText = (Text)e.widget;
//				System.out.println("获得焦点"+targetText.getData("identifier"));
//				
//			}
//		});
		text.addModifyListener(new ModifyListener() {
			
			@Override
			public void modifyText(ModifyEvent e) {
				Text targetText = (Text)e.widget;
				String fieldName = (String)targetText.getData("identifier");
				System.out.println("modifyText: " + fieldName);
				try {
					setter(sshSetting, fieldName, targetText.getText(), String.class);
					System.out.println(sshSetting.getHost());
				}catch (SecurityException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IllegalArgumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		return text;
	}
	

}
